﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Aliyeye.Car.Net.Utility
{
    public static class DateTimeExtensions
    {
        public static DateTime FirstDayOfThisWeek(this DateTime owner)
        {
            return owner.Date.AddDays(-(int)owner.DayOfWeek);
            
        }
        public static DateTime LastDayOfThisWeek(this DateTime owner)
        {
            return owner.Date.AddDays(6 - (int)owner.DayOfWeek);
        }

        public static DateTime FirstDayOfThisMonth(this DateTime owner)
        {
            return owner.Date.AddDays(-owner.Day + 1);
        }

        public static DateTime LastDayOfThisMonth(this DateTime owner)
        {
            return owner.Date.AddDays(DateTime.DaysInMonth(owner.Year, owner.Month) - owner.Day);
        }

        public static int DaysInQuarter(this DateTime owner)
        {
            int month = owner.Month;
            int ret=0;
            int mod = month % 3 ;
            int fix = mod;

            if (mod == 0)
            {
                fix = 3;
            }

            int startMonth = month - fix;

            for (int i = 0; i < 3; i++)
            {
                int currentMonth = startMonth + 1 + i;
                ret += DateTime.DaysInMonth(owner.Year, currentMonth);
            }

            return ret;
        }

        public static int DayOfQuarter(this DateTime owner)
        {
            int month = owner.Month;
            int ret = 0;
            int mod =  month % 3;
            int fix = mod;

            if (mod == 0)
            {
                fix = 3;
            }

            int startMonth = month - fix;

            for (int i = 1; i < fix; i++)
            {
                ret += DateTime.DaysInMonth(owner.Year, startMonth + i);
            }

            // add current day of month
            ret += owner.Day;

            return ret;
        }

        public static DateTime FirstDayOfThisQuarter(this DateTime owner)
        {
            return owner.Date.AddDays(-owner.DayOfQuarter() + 1);
        }

        public static DateTime LastDayOfThisQuarter(this DateTime owner)
        {
            return owner.Date.AddDays(owner.DaysInQuarter() - owner.DayOfQuarter());
        }
    }
}
